package com.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.blog.mapper.UserMapper;
import com.blog.pojo.User;
import com.blog.service.UserService;
import com.blog.util.FaceUtils;
import com.blog.util.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;


@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 验证登录
     *
     * @param username
     * @param password
     * @return
     */
    @Override
    public User checkUser(String username, String password) {
        return userMapper.selectOne(new QueryWrapper<User>()
                .eq("username", username)
                .eq("password", MD5Utils.digest(password)));
    }

    @Override
    public User FcheckUser(String username, String password) {
        return userMapper.selectOne(new QueryWrapper<User>()
                .eq("username", username)
                .eq("password", password));
    }

    @Override
    public User checkFace(MultipartFile photo) {
        User user = null;
        if (!photo.isEmpty()) {
            try {
                // 生成文件名
                String fileName = photo.getOriginalFilename();
                //获取项目地址
                String projectDir = new File(".").getCanonicalPath();
                // 指定文件保存路径
                String filePath = projectDir + "\\logs\\" + fileName;
                // 创建文件对象
                File dest = new File(filePath);
                // 保存文件
                photo.transferTo(dest);
                String username =  new FaceUtils().searchFace(filePath);
                user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
            } catch (IOException e) {
                e.printStackTrace();
                return user;
            }
        } else {
            return user;
        }
        return user;
    }


    @Override
    public void addUser(String username, String password) {
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        userMapper.insert(user);
}

    @Override
    public boolean isUserExists(String username) {
        // 使用 MyBatis Plus 的 QueryWrapper 进行条件查询
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));

        // 如果user不为null，说明用户名存在
        return user != null;
    }

}
